$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'exam/simulationexamination/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true , hidden:true},
			{ label: '考试名字', name: 'examinationName', index: 'examination_name', width: 80 }, 			
			{ label: '考试部门id', name: 'examinationDeptId', index: 'examination_dept_id', width: 80, hidden:true}, 			
			{ label: '考试部门', name: 'deptName', index: 'deptName', width: 80 }, 			
			{ label: '考试专业id', name: 'majorId', index: 'major_id', width: 80, hidden:true}, 			
			/*{ label: '考试专业', name: 'majorName', index: 'majorName', width: 80 }, */			
			/*{ label: '试卷id', name: 'paperId', index: 'paper_id', width: 80 },*/		
			{ label: '考试开始时间', name: 'examinationStartTime', index: 'examination_start_time', width: 80 }, 			
			{ label: '考试结束时间', name: 'examinationEndTime', index: 'examination_end_time', width: 80 }, 			
			{ label: '可考次数', name: 'examinationNumber', index: 'examination_number', width: 80 },
			{ label: '过关分数', name: 'examinationPassScore', index: 'examination_pass_score', width: 80 },
			/*{ label: '考试时长', name: 'examinationTimeLong', index: 'examination_time_long', width: 80 }, 			
			{ label: '考试注意事项', name: 'examinationAttention', index: 'examination_attention', width: 80 }, 			
			{ label: '二维码内容', name: 'qrCode', index: 'qr_code', width: 80 },*/ 			
			{ label: '考试状态', name: 'examinationState', index: 'examination_state', width: 80 , formatter: function(value, options, row){
				return value === 1 ? 
						'<span class="label label-danger" value="1">已发布</span>' : 
						'<span class="label label-success" value="0">未发布</span>';
			}}, 
			{ label: '考试状态', name: 'examinationState', index: 'examination_state', width: 80 , hidden:true}, 
			{ label: '创建时间', name: 'createTime', index: 'create_time', width: 90 , formatter:function(value,options,row){
                return new Date(value).Format('yyyy-MM-dd HH:mm:ss');}},  			
			/*{ label: '修改时间', name: 'updateTime', index: 'update_time', width: 80 },*/ 			
			 			
			{ label: '创建部门id', name: 'deptId', index: 'dept_id', width: 80 , hidden:true},			
			{ label: '状态', name: 'disFlag', index: 'dis_flag', width: 80 , hidden:true, formatter: function(value, options, row){
				return value === 1 ? 
						'<span class="label label-danger" value="1">禁用</span>' : 
						'<span class="label label-success" value="0">启用</span>';
			}},
			{ label: '创建人', name: 'createName', index: 'createName', width: 80 }			
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "simulationExamination.list",
            page: "simulationExamination.pageNum",
            total: "simulationExamination.pages",
            records: "simulationExamination.total"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
    
    $('.summernote').summernote({
		height : '220px',
		lang : 'zh-CN',
		callbacks: {
            onImageUpload: function(files, editor, $editable) {
                sendFile(files);
            }
        }
	});

});

/*var setting = {
		  data: {
		      simpleData: {
		         enable: true,
		         idKey: "deptId",
		         pIdKey: "parentId",
		         rootPId: -1
		        },
		      key: {
		         url:"nourl"
		      }
		  }
	};*/

var setting = {
	check: {
		enable: true,
			chkStyle: "checkbox",  //这里设置是否显示复选框
			chkboxType: { "Y": "", "N": "" }  //设置复选框是否与 父/子 级相关联
	},
	data: {
		simpleData: {
			enable: true,
			idKey: "deptId",
			pIdKey: "parentId",
			rootPId: -1
		},
		key: {
			url:"nourl"
		}
	}
};


var vm = new Vue({
	el:'#rrapp',
	data:{
		majorLists:{},
		paperList:{},
		showList: true,
		title: null,
        highestPassScore: 0, // 最高过关分数，选择试卷的总分数.
		simulationExamination: {deptName:null, examinationDeptId:null}
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.simulationExamination = {deptName:null, examinationDeptId:null};
			vm.getMajorList();
			vm.getDept();
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}

			//使用公用方法获取选中的数据.
			var rowData =getRowData(id);
			var state=rowData.examinationState;
			if(state!=0){
				layer.msg("试卷已发布，不允许修改");
				return ;
			}

			vm.showList = false;
            vm.title = "修改";
			vm.getMajorList();
            vm.getDept();
			vm.getInfo(id);
		},
		getDept: function(){
			//加载部门树
			$.get(baseURL + "sys/dept/list", function(r){
				ztree = $.fn.zTree.init($("#deptTree"), setting, r);
				var node = ztree.getNodeByParam("deptId", vm.simulationExamination.deptId);
				if(node != null){
					ztree.selectNode(node);
					//修改时，不能回显.下边的解决了.
					//vm.workDaily.deptName = node.name;
					Vue.set(vm.simulationExamination, 'deptName', node.name)
				}
			})
		},
		deptTree: function(){
	        layer.open({
	            type: 1,
	            offset: '50px',
	            skin: 'layui-layer-molv',
	            title: "选择部门",
	            area: ['300px', '450px'],
	            shade: 0,
	            shadeClose: false,
	            content: jQuery("#deptLayer"),
	            btn: ['确定', '取消'],
	            btn1: function (index) {
	                /*var node = ztree.getSelectedNodes();
	                //选择上级部门
	                vm.simulationExamination.examinationDeptId = node[0].deptId;
	                vm.simulationExamination.deptName = node[0].name;*/
					var nodes = ztree.getCheckedNodes(true);
					var examinationDeptId='';
					var deptName='';
					for (var i = 0; i <nodes.length ; i++) {
						if(i!=0){
							examinationDeptId+=',';
							deptName+=',';
						}
						examinationDeptId+=nodes[i].deptId;
						deptName+=nodes[i].name;
					}
					vm.simulationExamination.examinationDeptId = examinationDeptId;
					vm.simulationExamination.deptName = deptName;
	                layer.close(index);
	            }
	        });
	    },

		saveOrUpdate: function (event) {
            var url = vm.simulationExamination.id == null ? "exam/simulationexamination/save" : "exam/simulationexamination/update";
            vm.simulationExamination.examinationStartTime= $("#examinationStartTime").val();
            vm.simulationExamination.examinationEndTime= $("#examinationEndTime").val();
            vm.simulationExamination.examinationAttention = $("#examinationAttention").summernote('code');

            //  校验参数.
            if(!this.checkParam()) {
                return false;
            }

			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.simulationExamination),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			//使用公用方法获取选中的数据.
			var rowData =getRowData(ids);
			var state=rowData.examinationState;
			if(state!=0){
				layer.msg("试卷已发布，不允许删除!!!");
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "exam/simulationexamination/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "exam/simulationexamination/info/"+id, function(r){
                vm.simulationExamination = r.simulationExamination;
              //给富文本编辑器赋值.
    			$('#examinationAttention').summernote('code', vm.simulationExamination.examinationAttention);
            });
		},
		generateRq: function(event){
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			
			//使用公用方法获取选中的数据.
			var rowData =getRowData(id);
			var state=rowData.examinationState;
			
			vm.simulationExamination.id=id;
			
			if(state!=0){
				confirm('确定要取消发布考试选中的记录？', function(){
					$.ajax({
						type: "POST",
					    url: baseURL + "exam/simulationexamination/cancel",
	                    contentType: "application/json",
	                    data: JSON.stringify(vm.simulationExamination),
					    success: function(r){
							if(r.code == 0){
								alert('操作成功', function(index){
									$("#jqGrid").trigger("reloadGrid");
								});
							}else{
								alert(r.msg);
							}
						}
					});
				});
			}else{
				
				confirm('确定要发布考试选中的记录？', function(){
					$.ajax({
						type: "POST",
						url: baseURL + "exam/simulationexamination/generateRq/",
						contentType: "application/json",
						data: JSON.stringify(id),
						success: function(r){
							if(r.code == 0){
								alert('操作成功', function(index){
									$("#jqGrid").trigger("reloadGrid");
								});
							}else{
								alert(r.msg);
							}
						}
					});
				});
			}
			
		},
		seeRq: function(event){
			var id = getSelectedRows();
			//使用公用方法获取选中的数据.
			var rowData =getRowData(id);
			var state=rowData.examinationState;
			if(id == null){
				return ;
			}
			if(state!=1){
				layer.msg("试卷没有发布");
				return ;
			}
			$.get(baseURL + "exam/simulationexamination/find/"+id, function(r){
				if (r.code==0) {
					var data = r.data;
					if(data != null &&data != '') {
						var qrcode = data.qrCode;
						layer.open({
							title : '模拟考试名称：'+data.examinationName,
							type: 1,
							skin: 'layui-layer-rim', //加上边框
							area: ['400px', '400px'], //宽高
							content: '<div><img src="data:image/jpg;base64,'+qrcode+'" /></div>'
						});
						
					}
				}else{
					layer.msg(r.msg);
				}
			});
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page
            }).trigger("reloadGrid");
		},
		//获取专业列表.
		getMajorList: function (event) {
			$.get(baseURL + "exam/major/getList", function(r){
				vm.majorLists = r.majorList;
            });
		},
		//根据专业获取已发布试卷.
		getPaperList: function (majorId) {
			/*var majorId="001";*/
			var data = {majorId:majorId};
			$.get(baseURL + "exam/paperDesign/getList",data, function(r){
				vm.paperList = r.data;
            });
		},
        // 根据试卷，获取试卷id.
        setHighestPassScore: function (paperId) {
			var paperList = vm.paperList;
			if (paperList == null || paperList == undefined || paperList.length == 0 ) {
                vm.highestPassScore = 0;
			}
			for (var i =0 ;i < paperList.length; i++ ) {
                var paperObj = paperList[i];
                if (paperObj == null || paperObj == undefined) {
                    vm.highestPassScore = 0;
                }
                if (paperObj != null && paperObj != undefined && paperObj.id == paperId) {
                	vm.highestPassScore = paperObj.totalScore;
				}
			}
        },
        // ===================校验参数=========================== 校验参数 ===============================校验参数==================
        checkParam: function() {
            if (vm.simulationExamination.examinationDeptId == undefined || vm.simulationExamination.examinationDeptId == null) {
                //alert("请选择所属部门！");
                tips('请选择所属部门！', 'examinationDeptId');
                scrollto("#examinationDeptId");
                return false;
            } else if (vm.simulationExamination.majorId == undefined || vm.simulationExamination.majorId == null) {
                tips('请选择专业名称！', 'majorId');
                scrollto("#majorId");
                return false;
            } else if (vm.simulationExamination.paperId == undefined || vm.simulationExamination.paperId == null) {
                tips('请选择试卷！', 'paperId');
                scrollto("#paperId");
                return false;
            } else if (vm.simulationExamination.examinationName == undefined || vm.simulationExamination.examinationName == null || vm.simulationExamination.examinationName == "") {
                tips('请输入考试名字！', 'examinationName');
                scrollto("#examinationName");
                return false;
            } else if (vm.simulationExamination.examinationStartTime == undefined || vm.simulationExamination.examinationStartTime == null || vm.simulationExamination.examinationStartTime == "") {
                tips('请选择考试开始时间！', 'examinationStartTime');
                scrollto("#examinationStartTime");
                return false;
            } else if (vm.simulationExamination.examinationEndTime == undefined || vm.simulationExamination.examinationEndTime == null || vm.simulationExamination.examinationEndTime == "") {
                tips('请选择考试结束时间！', 'examinationEndTime');
                scrollto("#examinationEndTime");
                return false;
            } else if (vm.simulationExamination.examinationNumber == undefined || vm.simulationExamination.examinationNumber == null
                || vm.simulationExamination.examinationNumber == "" || vm.simulationExamination.examinationNumber < 0) {
                tips('请输入可考次数！', 'examinationNumber');
                scrollto("#examinationName");
                return false;
            } else if (!/^\+?[1-9][0-9]*$/.test(vm.simulationExamination.examinationNumber) || vm.simulationExamination.examinationNumber.length < 1 || vm.simulationExamination.examinationNumber.length > 8) {
                tips('可考次数为1~8位数字！', 'examinationNumber');
                scrollto("#examinationName");
                return false;
            } else if (vm.simulationExamination.examinationPassScore == undefined || vm.simulationExamination.examinationPassScore == null
                || vm.simulationExamination.examinationPassScore == "" || vm.simulationExamination.examinationPassScore < 0) {
                tips('请输入过关分数！', 'examinationPassScore');
                scrollto("#examinationPassScore");
                return false;
            }  else if (!/^\+?[1-9][0-9]*$/.test(vm.simulationExamination.examinationPassScore) || vm.simulationExamination.examinationPassScore.length < 1 || vm.simulationExamination.examinationPassScore.length > 4) {
                tips("过关分数为1~4位数字，试卷的最高分数为："+ vm.highestPassScore + "， 过关分数不能高于此分数！", 'examinationPassScore');
                scrollto("#examinationPassScore");
                return false;
            } else if (parseInt(vm.simulationExamination.examinationPassScore, 10) > parseInt(vm.highestPassScore, 10)) {
                tips("试卷的最高分数为："+ vm.highestPassScore + "， 过关分数不能高于此分数！", 'examinationPassScore');
                scrollto("#examinationPassScore");
                return false;
            } else if (vm.simulationExamination.examinationTimeLong == undefined || vm.simulationExamination.examinationTimeLong == null
                || vm.simulationExamination.examinationTimeLong == "" || vm.simulationExamination.examinationTimeLong < 0) {
                tips('请输入考试时长！', 'examinationTimeLong');
                scrollto("#examinationTimeLong");
                return false;
            }  else if (!/^\+?[1-9][0-9]*$/.test(vm.simulationExamination.examinationTimeLong) || vm.simulationExamination.examinationTimeLong.length < 1 || vm.simulationExamination.examinationTimeLong.length > 4) {
                tips('考试时长为1~4位数字！', 'examinationTimeLong');
                scrollto("#examinationTimeLong");
                return false;
            }
            return true;
        }
	},
	mounted: function(){
        laydate.render({
           elem: '#examinationStartTime', //指定元素
           type: 'datetime',
           istime: true,
           choose: function(dates){ // 选择日期完毕的回调
        	   vm.examination.examinationStartTime=dates;
           }
       });
        laydate.render({
            elem: '#examinationEndTime', //指定元素
            istime: true,
            type: 'datetime'
        });
   }
});

Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "H+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

